<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-03-16 10:34:03
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-12-06 14:21:15
 * @FilePath: \sys\src\views\SmartPasture\Food\FoodFile\components\See.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { PropType, reactive, ref, unref } from 'vue'
import { Descriptions } from '@/components/Descriptions'
import { ContentWrap } from '@/components/ContentWrap'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { useTable } from '@/hooks/web/useTableTest'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
import {
  spForageSpecsListApi,
  spForageSpecsDelApi,
  spForageSpecsAddAdminApi,
  spForageSpecsEditApi
} from '@/api/sp/food'
import Edit from './EditSku.vue'
import Log from './Log.vue'
const userInfo: any = wsCache.get('userInfo')
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})

const spForageSpecsList = (val) => {
  val.forage_id = props.currentRow?.id
  return spForageSpecsListApi(val)
}

// 相关规格数据查询
const specsDataTable = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spForageSpecsList,
  response: {
    data: 'data',
    count: 'count'
  }
})

// 表格数据
const specsDataCrudSchemas = reactive<CrudSchema[]>([
  {
    field: 'name',
    label: '规格名称'
  },
  {
    field: 'number',
    label: '净含量（公斤）'
  },
  {
    field: 'total_stock',
    label: '总库存'
  },
  {
    field: 'available_stock',
    label: '可用库存'
  },
  {
    field: 'lock_stock',
    label: '锁定库存'
  },
  // {
  //   field: 'unit',
  //   label: '单位',
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return cellValue != '0' ? getDictLabel('unit', cellValue) : ' '
  //   }
  // },
  {
    field: 'action',
    width: 290,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])
const specsDataRegister = specsDataTable.register
const specsDataTableObject = specsDataTable.tableObject
const titleData: any = ref(props.currentRow)
const specsDataMethods = specsDataTable.methods

const specsDataAllSchemas = useCrudSchemas(specsDataCrudSchemas).allSchemas
const actionType = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editRef = ref<ComponentRef<typeof Edit>>()
const logRef = ref<ComponentRef<typeof Log>>()
const loading = ref(false)

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add':
      dialogTitle.value = '新增'
      specsDataTableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'edit':
      dialogTitle.value = '修改'
      specsDataTableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'stockRecords':
      // push({
      //   path: '/smartPasture/food/foodgotou',
      //   query: {
      //     forage_id: row.forage_id,
      //     forage_sku_id: row.id
      //   }
      // })
      const sku = row.name ? row.name : ''
      dialogTitle.value = titleData.value.name + sku + '-出入库记录'
      specsDataTableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      if (row.total_stock > 0) {
        ElMessage({
          message: '该规格有库存，不可删除',
          type: 'warning'
        })
      } else {
        ElMessageBox.confirm('确定要删除这个饲料规格吗？', '删除', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            apiDel(row.id)
          })
          .catch(() => {})
      }
      break
    default:
      console.log('未知类型')
  }
}
const save = async () => {
  const write = unref(editRef)
  switch (actionType.value) {
    case 'add':
      await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = await write?.getFormData()
          const res = await spForageSpecsAddAdminApi({
            ...data,
            pasture_org_id: props.currentRow?.pasture_org_id,
            my_dept_id: userInfo.default_dept_id,
            forage_id: props.currentRow?.id
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            specsDataTableObject.currentPage = 1
            specsDataGetList()
          }
        }
      })
      break
    case 'edit':
      await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = await write?.getFormData()
          const res = await spForageSpecsEditApi({
            ...data,
            pasture_org_id: props.currentRow?.pasture_org_id
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            specsDataTableObject.currentPage = 1
            specsDataGetList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (val) => {
  let delRes = await spForageSpecsDelApi({ id: val })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    specsDataGetList()
  }
}

const specsDataGetList = specsDataMethods.getList
specsDataGetList() //查询相关组织列表
</script>

<template>
  <ContentWrap title="主数据">
    <Descriptions :schema="props.detailSchema" :data="currentRow || {}" />
  </ContentWrap>
  <div class="p-10px">
    <ContentWrap title="相关饲料包装率">
      <div class="mb-10px">
        <ElButton type="primary" @click="action('add', {})">新增</ElButton>
      </div>
      <Table
        v-model:pageSize="specsDataTableObject.pageSize"
        v-model:currentPage="specsDataTableObject.currentPage"
        :columns="specsDataAllSchemas.tableColumns"
        :data="specsDataTableObject.tableList"
        :loading="specsDataTableObject.loading"
        :pagination="{
          total: specsDataTableObject.count
        }"
        @register="specsDataRegister"
        :selection="false"
      >
        <template #action="{ row }">
          <ElButton type="primary" @click="action('stockRecords', row)"> 出入库记录 </ElButton>
          <ElButton type="warning" @click="action('edit', row)" title="删除"> 修改 </ElButton>
          <ElButton type="warning" @click="action('del', row)" title="删除"> 删除 </ElButton>
        </template>
      </Table>
    </ContentWrap>
  </div>
  <ContentWrap title="明细数据">
    <ElButton type="primary" @click="action('stockRecords', {})">查看出入库记录</ElButton>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'add'" ref="editRef" />
    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :current-row="specsDataTableObject.currentRow"
    />
    <Log
      v-if="actionType == 'stockRecords'"
      ref="logRef"
      :current-row="specsDataTableObject.currentRow"
      :titleData="titleData"
    />
    <template #footer>
      <ElButton
        v-if="actionType !== 'stockRecords'"
        type="primary"
        :loading="loading"
        @click="save"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
